package com.imay.live.activity.camera;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;

import com.imay.capturefilter.R;
import com.imay.capturefilter.adapter.FilterImageAdapter;
import com.imay.capturefilter.filter.base.gpuimage.GPUImage;
import com.imay.capturefilter.utils.ICCons;
import com.imay.capturefilter.utils.ICUtils;
import com.imay.capturefilter.utils.MagicFilterTools;
import com.imay.capturefilter.widget.ClipImageView;
import com.imay.capturefilter.widget.ICAutoAdjustRecylerView;
import com.imay.live.Constants;
import com.imay.live.activity.dynamics.ReleaseActivity;
import com.imay.live.analytics.MobclickAgent;
import com.imay.live.helper.DialogFragmentHelper;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;

public class ClipActivity extends FragmentActivity implements View.OnClickListener {

    private Context mContext = this;

    private ClipImageView mClipImageView;   //预览图

    private ICAutoAdjustRecylerView mRecyclerView;
    private FilterImageAdapter mAdapter;

    private MagicFilterTools mFilterTools;
    private GPUImage mGPUImage;

    private String mFilePath = "";

    private Bitmap mBitmap; //这是原图

    private boolean mIsFinish = true;
    private boolean mIsUri = false;

    private int mDegree;    // 图片被旋转的角度
    private int mSampleSize;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.capturefilter_activity_clip_image);

        mFilePath = getIntent().getStringExtra(ICCons.KEY_FILE_PATH);
        String uri = getIntent().getStringExtra(ICCons.KEY_FILE_URI);
        if (!TextUtils.isEmpty(uri)) {
            mFilePath = ICUtils.getPathByUri(this, Uri.parse(uri));
            mIsUri = true;
        }
        DialogFragmentHelper.showLoadingDialog(getSupportFragmentManager(),getString(R.string.IC_img_msg_filter_loading));
        initView();
        initData();
        MobclickAgent.onEvent(ClipActivity.this,"photo_edit_open");
    }

    private void initView() {
        findViewById(R.id.iv_close).setOnClickListener(this);   //取消裁剪
        findViewById(R.id.iv_clip).setOnClickListener(this);   //确认裁剪

        mGPUImage = new GPUImage(this);
        mFilterTools = MagicFilterTools.getInstance(ClipActivity.this);//初始化滤镜数据

        mClipImageView = (ClipImageView) findViewById(R.id.clip_image_view);    //预览图

        mRecyclerView = (ICAutoAdjustRecylerView) findViewById(R.id.recyclerView);    //滤镜列表

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayout.HORIZONTAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.setPxPerMillsec(1.0f);
        mAdapter = new FilterImageAdapter(this);
        mAdapter.setNames(mFilterTools.getFilterNames(ClipActivity.this));
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setItemOnClickListener(new FilterImageAdapter.AutoAdjustItemClickListener() {
            @Override
            public void onItemClick(View view, final int postion) {
                if (postion == 1) {
                    MobclickAgent.onEvent(ClipActivity.this, "photo_click_sticker_1");
                } else if (postion == 2) {
                    MobclickAgent.onEvent(ClipActivity.this, "photo_click_sticker_2");
                } else if (postion == 3) {
                    MobclickAgent.onEvent(ClipActivity.this, "photo_click_sticker_3");
                } else if (postion == 4) {
                    MobclickAgent.onEvent(ClipActivity.this, "photo_click_sticker_4");
                } else if (postion == 5) {
                    MobclickAgent.onEvent(ClipActivity.this, "photo_click_sticker_5");
                } else if (postion == 6) {
                    MobclickAgent.onEvent(ClipActivity.this, "photo_click_sticker_6");
                } else if (postion == 7) {
                    MobclickAgent.onEvent(ClipActivity.this, "photo_click_sticker_7");
                } else if (postion == 8) {
                    MobclickAgent.onEvent(ClipActivity.this, "photo_click_sticker_8");
                } else if (postion == 9) {
                    MobclickAgent.onEvent(ClipActivity.this, "photo_click_sticker_9");
                } else if (postion == 10) {
                    MobclickAgent.onEvent(ClipActivity.this, "photo_click_sticker_10");
                }

                if (!mIsFinish) return;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        mIsFinish = false;
                        mGPUImage.setImage(mBitmap);
                        mGPUImage.setFilter(mFilterTools.getGPUImageFilter(mContext, postion));

                        mHandler.sendMessage(setCurrImgBitmapToFilter());
                        mAdapter.setSelectedPostion(postion);
                        mRecyclerView.checkAutoAdjust(postion);
                        mIsFinish = true;
                    }
                }).start();
            }
        });
    }

    private Message setCurrImgBitmapToFilter() {
        Bitmap tempBitmap = mGPUImage.getBitmapWithFilterApplied();
        Message msg = new Message();
        msg.what = 3;
        msg.obj = tempBitmap;
        return msg;
    }

    private void initData() {
        mClipImageView.setmInput(mFilePath);
        setImageAndClipParams();
    }

    /**
     * 大图裁剪
     */
    private void setImageAndClipParams() {
        mClipImageView.post(new Runnable() {
            @Override
            public void run() {
                mDegree = ICUtils.readPictureDegree(mFilePath);
                final boolean isRotate = (mDegree == 90 || mDegree == 270);

                final BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(mFilePath, options);

                // 如果图片被旋转，则宽高度置换
                int w = isRotate ? options.outHeight : options.outWidth;

                // 裁剪是宽高比例3:2，只考虑宽度情况，这里按border宽度的两倍来计算缩放。
                mSampleSize = ICUtils.findBestSample(w, mClipImageView.getClipBorder().width());

                options.inJustDecodeBounds = false;
                options.inSampleSize = mSampleSize;
                options.inPreferredConfig = Bitmap.Config.RGB_565;
                final Bitmap source = BitmapFactory.decodeFile(mFilePath, options);

                if (source == null) {
                    mHandler.sendEmptyMessage(5);
                    return;
                }

                // 解决图片被旋转的问题
                if (mDegree == 0) {
                    mBitmap = source;
                } else {
                    final Matrix matrix = new Matrix();
                    matrix.postRotate(mDegree);
                    mBitmap = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, false);
                    if (mBitmap != source && !source.isRecycled()) {
                        source.recycle();
                    }
                }
                mClipImageView.setImageBitmap(mBitmap);
                mHandler.sendEmptyMessage(4);
            }
        });
    }

    // 滤镜缩略图
    private void initBitmapList(final Bitmap thumbBitmap) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (mFilterTools.getFilterNames(ClipActivity.this) == null)
                    mFilterTools = MagicFilterTools.getInstance(ClipActivity.this);
                ArrayList<Bitmap> mBitmapList = new ArrayList<>();
                final int size = mFilterTools.getFilterNames(ClipActivity.this).size();
                for (int i = 0; i < size; i++) {
                    if (thumbBitmap == null)
                        break;
                    try {
                        mGPUImage.setImage(thumbBitmap);   //滤镜设置缩略图
                        mGPUImage.setFilter(mFilterTools.getGPUImageFilter(mContext, i));
                        mBitmapList.add(mGPUImage.getBitmapWithFilterApplied());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                ICUtils.recycledBitmap(thumbBitmap);
                mAdapter.setBitmapList(mBitmapList);
                Message msg = new Message();
                //msg.obj = mDialog;
                msg.what = 0;
                mHandler.sendMessage(msg);
            }
        }).start();
    }

    @Override
    public void onClick(View v) {
        final int id = v.getId();
        if (id == R.id.iv_close) {
            finish();
        } else if (id == R.id.iv_clip) {
            clipImage();
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 4:
                    Bitmap thumbBitmap = ThumbnailUtils.extractThumbnail(mBitmap, 75, 75);    //得到缩略图
                    initBitmapList(thumbBitmap);   //初始化滤镜列表
                    break;
                case 0:
                    mAdapter.notifyDataSetChanged();
                    DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
                    break;
                case 2:
                    DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
                    //刷新文件夹
                    String resultFilePath = (String) msg.obj;
                    refreshPicture(resultFilePath);

                    findViewById(R.id.iv_clip).setEnabled(true);//禁止重复点击

                    ReleaseActivity.startActivity(ClipActivity.this,resultFilePath,null,null,ReleaseActivity.IMAGE, Constants.DYNAMICSFEED_REQUEST_CODE);
                    break;
                case 3:
                    if (msg.obj != null && msg.obj instanceof Bitmap) {
                        Bitmap bitmap = (Bitmap) msg.obj;
                        mClipImageView.setImageBitmap(bitmap);
                        mAdapter.notifyDataSetChanged();
                    }
                    break;
                case 5: //原图资源文件失败，原始数据是空的
                    try {
                        ICUtils.showToast(mContext, getResources().getString(R.string.IC_img_msg_source_error));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    onBackPressed();
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    public void finish() {
        if (!mIsUri) {    //相册选择，不删除原文件
            ICUtils.deleteFile(ClipActivity.this, mFilePath);//裁剪OK,删除原文件
        }
        super.finish();
    }

    private void refreshPicture(String filePath) {
        if (ICUtils.hasKitkat()) {
            ICUtils.scanPhotos(filePath, this);
        } else {
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            intent.setData(Uri.fromFile(new File(filePath)));
            sendBroadcast(intent);
        }
    }

    private void clipImage() {
        findViewById(R.id.iv_clip).setEnabled(false);//禁止重复点击
        DialogFragmentHelper.showLoadingDialog(getSupportFragmentManager(),getString(R.string.IC_img_msg_cilp));
        new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap tempBitmap = ((BitmapDrawable) mClipImageView.getDrawable()).getBitmap();
                if (tempBitmap == null) {
                    tempBitmap = mBitmap;
                }
                Bitmap b = mClipImageView.createClippedBitmap(ICUtils.bmpToByteArray(tempBitmap, false));
//                Bitmap water = BitmapFactory.decodeResource(getResources(),R.mipmap.ioc_00_log_shuiyin);
//                b = ImageUtil.createWaterMaskRightBottom(mContext,b,water,10,10);

                String path = saveImage(b);

//                if (!b.isRecycled()) {
//                    b.recycle();
//                }
//                if(!water.isRecycled()){
//                    water.recycle();
//                }
                Message message = Message.obtain();
                message.obj = path;
                message.what = 2;
                mHandler.sendMessage(message);
            }
        }).start();
    }

    private String saveImage(final Bitmap image) {
        File file = ICUtils.getOutputMediaFile(mContext);
        try {
            image.compress(Bitmap.CompressFormat.JPEG, 80, new FileOutputStream(file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return file.getAbsolutePath();
    }

    @Override
    public void onBackPressed() {
        if (!mIsUri) {    //相册选择，不删除原文件
            ICUtils.deleteFile(this, mFilePath);//取消或者Back键盘，也删除原文件
        }
        setResult(Activity.RESULT_CANCELED, getIntent());
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        // 释放图片资源
        final ArrayList<Bitmap> bitmapArrayList = mAdapter.getBitmapList();
        for (Bitmap bitmap : bitmapArrayList) {
            ICUtils.recycledBitmap(bitmap);
        }
        if (mBitmap != null) {
            ICUtils.recycledBitmap(mBitmap);
        }
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
}